package com.iwithlong.service.impl;

import com.imesne.assistant.common.bean.BeanKit;
import com.imesne.assistant.common.exception.ImesneException;
import com.imesne.assistant.common.page.PageList;
import com.imesne.assistant.common.utils.EncryptUtils;
import com.imesne.assistant.common.validation.Verifier;
import com.imesne.assistant.jdbc.command.entity.Select;
import com.imesne.assistant.jdbc.persist.JdbcDao;
import com.iwithlong.context.Constants;
import com.iwithlong.entity.Member;
import com.iwithlong.entity.MemberGrowthAccount;
import com.iwithlong.enums.MemberStatus;
import com.iwithlong.enums.MemberType;
import com.iwithlong.enums.Rank;
import com.iwithlong.event.MemberEvent;
import com.iwithlong.log.LogLevel;
import com.iwithlong.log.LogOperatorType;
import com.iwithlong.log.Logable;
import com.iwithlong.service.MemberService;
import com.iwithlong.vo.MemberVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Write class comments here
 * <p>
 * User: TJM
 * Date: 2017/10/10 19:01
 * version $Id: MemberServiceImpl.java, v 0.1  19:01 Exp $
 */
@Service
public class MemberServiceImpl implements MemberService{

	@Resource
	private JdbcDao jdbcDao;

	@Resource
	private ApplicationContext applicationContext;

	@Override
	public void delete (Long memberId) {
		jdbcDao.createDelete(MemberGrowthAccount.class).where("memberId", new Object[]{memberId}).execute();
		jdbcDao.createDelete(Member.class).where("memberId", new Object[]{memberId}).execute();
	}

	@Override
//	@Logable
	public void enable (Long memberId) {
		Member member = jdbcDao.get(Member.class, memberId);
		if (member == null) {
			throw new ImesneException ("当前会员不存在, 无法启用");
		}
		if (!StringUtils.equals(member.getStatus(), MemberStatus.DISABLED.getCode())) {
			throw new ImesneException("当前会员不是禁用状态, 无法启用");
		}
		member.setStatus(MemberStatus.ENABLED.getCode());
		jdbcDao.createUpdate(Member.class)
				.set("status", MemberStatus.ENABLED.getCode())
				.where("memberId", new Object[]{memberId})
				.execute();
//		LogUtil.setLogContent(LogOperatorType.MEMBER, "启用会员: " + member.getMemberName());

	}

	@Override
//	@Logable
	public void disable (Long memberId) {
		Member member = jdbcDao.get(Member.class, memberId);
		if (member == null) {
			throw new ImesneException("当前会员不存在, 无法禁用");
		}
		if (!StringUtils.equals(member.getStatus(), MemberStatus.ENABLED.getCode())) {
			throw new ImesneException("当前会员不是启用状态, 无法禁用");
		}
		member.setStatus(MemberStatus.DISABLED.getCode());
		jdbcDao.createUpdate(Member.class)
				.set("status", MemberStatus.DISABLED.getCode())
				.where("memberId", new Object[]{memberId})
				.execute();

//		LogUtil.setLogContent(LogOperatorType.MEMBER, "禁用会员: " + member.getMemberName());
	}

	@Override
	public Member get (Long memberId) {
		Verifier.init().notNull(memberId, "id").validate();
		return jdbcDao.get(Member.class, memberId);
	}

	@Override
	public List<MemberVo> pageList (MemberVo vo) {
		Select<Member> select = jdbcDao.createSelect(Member.class);

		PageList<Member> members = transCondition(select, vo).pageList(vo);

		return new PageList<>(BeanKit.convert(MemberVo.class, members), members.getPager());
	}


	private Select<Member> transCondition(Select<Member> select, MemberVo vo) {

		select.where("1", new Object[]{1});

		if (StringUtils.isNotEmpty(vo.getKeywords())) {
			select.and().begin()
					.condition("memberCode", "like", new Object[]{"%" + vo.getKeywords() + "%"})
					.or("memberName", "like", new Object[]{"%" + vo.getKeywords() + "%"})
					.or("mobile", "=", new Object[]{vo.getKeywords()})
					.end();
		}

		if (StringUtils.isNotEmpty(vo.getStatus())) {
			select.and("status", new Object[]{vo.getStatus()});
		}
		select.and("memberType",MemberType.MEMBER.getCode());
		select.orderBy("memberId").desc();

		return select;
	}

	@Override
	@Logable(logLeVel = LogLevel.CRITICAL, operatorType = LogOperatorType.MEMBER, logContent = "会员修改密码")
	public void modifyPassword (MemberVo loginMember, String newPassword, String oldPassword) {
		Verifier.init().notNull(loginMember, "登录会员")
				.notBlank(newPassword, "新密码")
				.notBlank(oldPassword, "旧密码")
				.validate();
		if (!StringUtils.equals(loginMember.getMemberPassword(), getPassword(loginMember.getMobile(), oldPassword))) {
			throw new ImesneException("原密码不正确!");
		}
		String newMd5Password = getPassword(loginMember.getMobile(), newPassword);

		int row = jdbcDao.createUpdate(Member.class)
				.set("memberPassword", newMd5Password)
				.where("memberId", new Object[]{loginMember.getMemberId()})
				.execute();
		if (row >= 1) {
			loginMember.setMemberPassword(newMd5Password);
		}
	}


	@Override
	public void validatePassword (String password, MemberVo loginMember) {
		if (!StringUtils.equals(loginMember.getMemberPassword(), getPassword(loginMember.getMobile(), password))) {
			throw new ImesneException("密码输入错误!");
		}
	}

	@Override
	public void updateMember (MemberVo memberVo) {
		Member member;
		if(memberVo.getMemberId ()==null){
			Select<Member> memberSelect = jdbcDao.createSelect(Member.class).where("1",1);
			memberSelect.and("weixin",memberVo.getWeixin());
			member = memberSelect.singleResult();
		}else {
			member = jdbcDao.get(Member.class, memberVo.getMemberId ());
		}

		if (StringUtils.isNotEmpty (memberVo.getMobile ())) {
			member.setMobile (memberVo.getMobile ());
		}
		if (StringUtils.isNotEmpty (memberVo.getMemberName ())) {
			member.setMemberName (memberVo.getMemberName ());
		}
		if (StringUtils.isNotEmpty (memberVo.getEmail ())) {
			member.setEmail (memberVo.getEmail ());
		}

		if (memberVo.getSex ()!=null) {
			member.setSex (memberVo.getSex ());
		}

		if (memberVo.getBirthday ()!=null) {
			member.setBirthday (memberVo.getBirthday ());
		}

		if (StringUtils.isNotEmpty (memberVo.getHead ())) {
			member.setHead (memberVo.getHead ());
		}

		if (StringUtils.isNotEmpty (memberVo.getNickName ())) {
			member.setNickName(memberVo.getNickName());
		}

		jdbcDao.update (member);
	}

	@Override
//	@Logable
	public MemberVo register (MemberVo vo) {
		Verifier.init().notBlank(vo.getWeixin (), "微信号").validate();

		vo.setStatus(MemberStatus.ENABLED.getCode());
		vo.setRank(Rank.V1.getCode());
		Member member = BeanKit.convert(new Member(), vo);
		member.setMemberType(MemberType.MEMBER.getCode());
		vo.setMemberId((Long) jdbcDao.insert(member));
		//注册事件
		applicationContext.publishEvent(new MemberEvent.Register(vo.getMemberId()));
//		LogUtil.setLogContent(LogOperatorType.MEMBER, "微信号： " + member.getWeixin() + "注册");

		return vo;
	}

	@Override
	public MemberVo login (String weixin) {

		Verifier.init().notBlank(weixin, "微信号").validate();
		Member member = jdbcDao.createSelect(Member.class)
				.where("weixin", new Object[]{weixin}).singleResult();
		if (member == null) {
			MemberVo vo=new MemberVo ();
			vo.setWeixin (weixin);
			return register(vo);
		}
		if (StringUtils.equals(MemberStatus.DISABLED.getCode(), member.getStatus())) {
			throw new ImesneException("会员已禁用!");
		}

		return BeanKit.convert(new MemberVo(), member);
	}

	@Override
	public MemberVo findByWeixin(String weixin) {
		Select<Member> select = jdbcDao.createSelect(Member.class).where("1",1);
		select.and("weixin", weixin);
		return BeanKit.convert(new MemberVo(),select.singleResult());
	}


	private String getPassword(String mobile, String password) {
		return EncryptUtils.getMD5(Constants.PASSWORD_PREFIX + mobile + password);
	}
}
